import request from "../request.js"
import cfg from "../config.js"
import tabs from "../tabs.js"
import utils from "../utils.js"
import page_ext from "../page/crud_page_ext.js"

//修改默认请求格式与后台匹配
function requestAdaptor(api, ignores) {
  let data = api.data;
  api.data = {
    filter: []
  }
  let keys = Object.keys(data);
  for (let key of keys) { //下面这些字段amis和查询条件混在了一起
    if (key == 'page') {
      api.data.page = data.page;
    }
    else if (key == 'perPage') {
      api.data.perpage = data.perPage;
    }
    else if (key == 'orderBy') {
      api.data.orderby = data.orderBy;
    }
    else if (key == 'orderDir') {
      api.data.orderdir = data.orderDir;
    }
    else if (key == 'keywords') {
      api.data.keywords = data.keywords;
    }
    else if(!ignores.includes(key)) {
      api.data.filter.push({
        key: key,
        value: data[key],
        like: true
      })
    }
  }
  return api;
}
let extjs = {};
let page_type = {
  open: function (page_info) {
    let page_html_id=page_info.page_html_id;
    let property=page_info.property;
    let ext_js=page_info.ext_js;
    let page_id=page_info.page_id;
    let rights=page_info.rights;
    let login_info=page_info.login_info;
    let params=page_info.params;
    extjs = page_ext[ext_js] ? page_ext[ext_js] : {}; //页面定制代码
    extjs.page_info=page_info;
    let datamodel = property.datamodel;
    extjs.datamodel=datamodel;
    let perpage = property.perpage ? property.perpage : 10;
    if (params && params.default_filter) property.default_filter = (property.default_filter?property.default_filter:[]).concat(params.default_filter);
    let path = "datamodel/getinfo";
    request(path, { datamodel: datamodel }, function (info) {
      let tablename = info.tablename;
      let modelname = info.modelname;
      extjs.tablename=tablename;
      extjs.modelname=modelname;
      let fields = info.fields;
      let rights = info.rights;
      let r_read = rights.查 ? rights.查 : false, r_add = rights.增 ? rights.增 : false, r_edit = rights.改 ? rights.改 : false, r_del = rights.删 ? rights.删 : false;
      if (!r_read) { alert("没有数据模型：" + modelname + " 的查看权限"); return; };
      let columns = [];
      let keywords_search_columns = [];
      let add_form_controls = [];
      let add_form_controls_group = {};
      //对列进行排序
      fields.sort(function (a, b) {
        let a_index = 15, b_index = 15;
        if (a.name == 'id') a_index = 0;
        if (b.name == 'id') b_index = 0;
        if (a.name == 'create_time') a_index = 21;
        if (b.name == 'create_time') b_index = 21;
        if (a.name == 'create_user') a_index = 22;
        if (b.name == 'create_user') b_index = 22;
        if (a.name == 'update_time') a_index = 23;
        if (b.name == 'update_time') b_index = 23;
        if (a.name == 'update_user') a_index = 24;
        if (b.name == 'update_user') b_index = 24;
        if (a_index == 15 || b_index == 15) {
          property.columns.forEach(c => {
            if (a_index == 15 && a.name == c.name && b_index != 11) a_index = 11;
            if (b_index == 15 && b.name == c.name && a_index != 11) b_index = 11;
            if (a_index == 15 && a.name == c.name && b_index == 11) a_index = 18;
            if (b_index == 15 && b.name == c.name && a_index == 11) b_index = 18;
          })
        }
        return a_index - b_index;
      });
      //打开编辑页
      function open_edit_page(a,b){
        let id = b.data.id;
        if (property.children) {
          for (let child of property.children) {
            child.this_field_value = b.data[child.this_field];
          }
        }
        let this_property = {
          id: id,
          datamodel: property.datamodel,
          model_table_name: property.model_table_name,
          columns: property.columns,
          children: property.children ? property.children : [],
          editable: r_edit && !property.dis_editable
        }
        let tab_id = "crud_" + datamodel + '_' + id;
        let tab_label = modelname + '记录(' + id + ')';
        tabs.open_by_page_type("tabs_container", tab_id, tab_label, "fa-edit", "children_edit_page_type", this_property)
      }
      //all fields
      let pre_group_no; //新增窗口分组用
      let pre_group; //新增窗口分组用
      for (let field of fields) {
        if (field.relater) continue; //被关联的字段不显示，源字段显示被关联字段的显示值
        let col = {
          name: field.name,
          label: (field.related && field.related.label) ? field.related.label : field.label,
          toggled: false
        }
        let keywords_col = {
          name: field.name
        }
        let add_form_control = {
          type: "text",
          name: col.name,
          label: col.label,
          className: "crud-add-form-item crud-add-form-item-" + col.name,
          required: field.required,
          value: field.default
        }
        //系统字段，除ID和创建时间外默认不显示
        if (field.name == "id" || field.name == "create_time") {
          col.toggled = true;
        }
        if (field.is_sys_field) {
          col.sortable = true;
          if (field.related) {
            col.type = "tpl"
            col.tpl = "${#" + col.name + "}"
          }
        }
        //页面属性有配置
        let property_column = property.columns ? property.columns.filter(c => c.name == field.name) : [];
        if (property_column.length > 0) {
          let prop = property_column[0];
          col.label = prop.label;
          col.sortable = prop.sortable;
          col.searchable = prop.searchable;
          col.quickEdit = prop.quickedit;
          col.toggled = !prop.hidden;
          //在新增窗口中不显示
          if(prop.not_in_add_form){
            add_form_control.visible=false;
          }
          ////各种字段类型处理
          if (prop.type == "textarea") {
            col.type = "text";
            col.quickEdit = false;
            add_form_control.type = "textarea";
            if (prop.quickedit) {
              col.quickEdit = {
                "type": "textarea"
              };
            }
          }
          else if ((prop.type == "number" || field.type == "number" || field.type == "int") && !field.related) {
            col.type = "text";
            col.quickEdit = false;
            add_form_control.type = "input-number";
            if (prop.quickedit) {
              col.quickEdit = {
                "type": "input-number"
              };
            }
          }
          else if (prop.type == "date" || field.type == "date") {
            col.type = "text";
            col.quickEdit = false;
            add_form_control.type = "input-date";
            add_form_control.format = "YYYY-MM-DD";
            add_form_control.valueFormat = "YYYY-MM-DD";
            if (prop.quickedit) {
              col.quickEdit = {
                "type": "input-date",
                "format": "YYYY-MM-DD",
                "valueFormat": "YYYY-MM-DD"
              };
            }
          }
          else if (prop.type == "datetime" || field.type == "datetime") {
            col.type = "text";
            col.quickEdit = false;
            add_form_control.type = "input-datetime";
            add_form_control.format = "YYYY-MM-DD HH:mm:ss";
            add_form_control.valueFormat = "YYYY-MM-DD HH:mm:ss";
            if (prop.quickedit) {
              col.quickEdit = {
                "type": "input-datetime",
                "format": "YYYY-MM-DD HH:mm:ss",
                "valueFormat": "YYYY-MM-DD HH:mm:ss"
              };
            }
          }
          else if (prop.type == "switch") {
            col.type = "switch";
            col.quickEdit = false;
            add_form_control.type = "switch";
          }
          else if (prop.type == "password" || field.type == "password") {
            col.type = "tpl";
            col.tpl = "****************";
            add_form_control.type = "input-password";
            if (prop.quickedit) {
              col.quickEdit = {
                "type": "input-password"
              };
            }
          }
          else if (prop.type == "file") { //文件
            col.type = "tpl";
            col.tpl = "<i class='fa fa-folder-o'></i>"
            let add_and_quick_edit_set = {
              "type": "input-file",
              "receiver" : cfg.file_server+"upload/"
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "image") { //图片
            col.type = "tpl";
            col.tpl = "<i class='fa fa-image'></i>"
            let add_and_quick_edit_set = {
              "type": "input-image",
              "receiver" : cfg.file_server+"upload/"
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "radios") { //单选列表
            let add_and_quick_edit_set = {
              "type": "radios",
              "options": prop.options
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "checkboxes") { //多选列表
            let add_and_quick_edit_set = {
              "type": "checkboxes",
              "options": prop.options
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (field.select) { //下拉选框
            let add_and_quick_edit_set = {
              "type": "select",
              "source": {
                "method": "post",
                "url": cfg.api_server + "options/get",
                "requestAdaptor": function (api) {
                  api.data = {
                    group: field.select.group
                  }
                }
              }
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑
          }
          else if (prop.type == "icon") { //图标选择
            col.type = "tpl"
            col.tpl = "<i class='fa ${" + col.name + "}'></i>"
            let add_and_quick_edit_set = {
              "type": "picker",
              "source": "/js/icons.json",
              "valueField": "value",
              "labelField": "value",
              "size": "lg",
              "pickerSchema": {
                "mode": "cards",
                "loadDataOnce": true,
                "affixHeader": false,
                "syncLocation": false,
                "perPage": 50,
                "name": "thelist",
                "className": "icon-picker",
                "card": {
                  "body": [
                    {
                      "type": "tpl",
                      "tpl": "<i class='fa ${value}' style='font-size:1.2rem'></i>"
                    }
                  ]
                }
              }
            }
            if (prop.quickedit) {
              col.quickEdit = add_and_quick_edit_set;
            }
            add_form_control = Object.assign(add_form_control, add_and_quick_edit_set); //添加时Form中的控件同编辑时的快速编辑，都是picker
          }
          else if (prop.type == "config") { //配置设置
            let api = undefined;
            let level = undefined;
            let disabled = true;
            let actions = [];
            if (col.quickEdit) {
              col.quickEdit = false;
              api = {
                "method": "post",
                "url": cfg.api_server + "datamodel/update",
                "requestAdaptor": function (api) {
                  let rowDiff = {
                    id: api.data.id
                  };
                  if (Object.keys(api.data).includes(col.name)) {
                    rowDiff[col.name] = api.data[col.name];
                  }
                  else if (Object.keys(api.data).includes("configer")) {
                    rowDiff[col.name] = JSON.stringify(api.data.configer);
                  }
                  let row = api.data;
                  let rowOrigin = api.data.pristine;
                  rowOrigin[col.name] = api.data.pristine[col.name];
                  api.data = {
                    "rows": [row],
                    "rowsDiff": [rowDiff],
                    "rowsOrigin": [rowOrigin]
                  }
                  api.data.datamodel = datamodel;
                  api.data.tablename = tablename;
                }
              };
              level = "success";
              disabled = false;
              actions = undefined;
            }
            let configer = prop.configer;
            let configer_api = prop.configer_api;
            let language = prop.language ? prop.language : "json";
            let operation_buttons = [];
            let config_edit_controls = [];
            let config_lang_edit_controls = [];
            if (configer || configer_api) {
              config_edit_controls.push(
                {
                  "type": "service",
                  "name": "configer",
                  "data": {
                    "api_server": cfg.api_server,
                    "report_server": cfg.report_server
                  },
                  "schemaApi": {
                    "method": "post",
                    "url": cfg.api_server + (configer_api ? configer_api : "configer/getbyname"),
                    "requestAdaptor": function (api) {
                      if (!configer_api) { //通过名称获取配置器
                        api.data.name = configer;
                        api.data.config_data = api.data[col.name];
                      }
                      else { //通过数据信息动态获取配置器
                        api.data.datamodel = datamodel;
                        api.data.page_id = page_id;
                        api.data.fieldname = field.name;
                        let row = {};
                        for (let field of fields) {
                          let key = field.name;
                          row[key] = api.data[key];
                        }
                        api.data.row = row;
                        api.data.config_data = api.data[col.name];
                      }
                    },
                    "adaptor": function (payload, response) {
                      if (!payload.data || !payload.data.controls || payload.data.controls.length == 0) {
                        let data = {}; data[col.name] = JSON.stringify(payload.data.data);
                        return {
                          "data": {
                            "controls": [
                              {
                                type: language + "-editor",
                                name: col.name,
                                size: "xxl",
                                required: field.required,
                                disabled: r_edit ? disabled : true
                              },
                            ],
                            "data": data
                          }
                        }
                      }
                      else {
                        payload.data.controls.push(
                          {
                            "type": "divider"
                          },
                          {
                            "type": "fieldSet",
                            "title": "JSON",
                            "collapsable": true,
                            "collapsed": true,
                            "body": [
                              {
                                "type": "static",
                                "tpl": "<pre>${configer|json}</pre>"
                              }
                            ]
                          }
                        )
                        return payload;
                      }
                    }
                  }
                }
              )
              operation_buttons.push(
                {
                  "type": "button",
                  "size": "xs",
                  "actionType": "dialog",
                  "label": "CONFIG",
                  "level": level,
                  "disabled": disabled,
                  "dialog": {
                    "title": modelname + "-" + col.label,
                    "size": "xl",
                    "actions": r_edit ? actions : [],
                    "body": {
                      "type": "form",
                      "name": "config_form",
                      "className": "config-form",
                      "mode": "normal",
                      "api": api,
                      "controls": [
                        {
                          type: "static",
                          name: "id",
                          label: "[ ${name} ] ID:",
                          mode: "inline"
                        },
                        ...config_edit_controls
                      ]
                    }
                  }
                }
              )
            }
            else {
              config_edit_controls.push(
                {
                  type: language + "-editor",
                  name: col.name,
                  size: "xxl",
                  required: field.required,
                  disabled: r_edit ? disabled : true
                }
              )
            }
            config_lang_edit_controls.push(
              {
                type: language + "-editor",
                name: col.name,
                size: "xxl",
                required: field.required,
                disabled: r_edit ? disabled : true
              }
            )
            operation_buttons.push(
              {
                "type": "button",
                "size": "xs",
                "actionType": "dialog",
                "label": language.toUpperCase(),
                "level": "secondary",
                "disabled": disabled,
                "dialog": {
                  "title": modelname + "-" + col.label,
                  "size": "xl",
                  "actions": r_edit ? actions : [],
                  "body": {
                    "type": "form",
                    "name": "config_form",
                    "mode": "normal",
                    "api": api,
                    "controls": [
                      {
                        type: "static",
                        name: "id",
                        label: "[ ${name} ] ID:",
                        mode: "inline"
                      },
                      ...config_lang_edit_controls
                    ]
                  }
                }
              }
            )
            col.type = "operation";
            col.buttons = [
              {
                "type": "button-group",
                "buttons": operation_buttons
              }
            ]
            add_form_control.type = "combo";
            add_form_control.multiLine = true;
            add_form_control.items = [
              ...config_edit_controls
            ]
          }
          else if (field.related) { //关联表选择
            col.type = "tpl"
            col.tpl = "<span class='label label-info'>${#" + col.name + "}</span>"
            col.autoFill = {};
            let that_label_field = field.related.that_label_field;
            let that_field = field.related.that_field;
            let select_columns = [] //新增或者编辑选择时界面显示的列，默认包含对方关联表的关联字段和关联显示字段
            let extra_columns = prop.related ? prop.related.extra_columns : undefined //配置中的增加选择列
            let orderby = prop.related ? prop.related.orderby : undefined //配置中的关联选择时的默认排序
            let orderdir = prop.related ? prop.related.orderdir : undefined //配置中的关联选择时的默认排序
            let filterby = prop.related ? prop.related.filterby : undefined //配置中的关联选择时的默认过滤
            let filtervalue = prop.related ? prop.related.filtervalue : undefined //配置中的关联选择时的默认过滤
            if (!extra_columns || extra_columns.filter(c => c.name == that_field).length == 0) {
              select_columns.push({
                "name": that_field,
                "label": field.label,
                "sortable": true
              })
            }
            if (!extra_columns || extra_columns.filter(c => c.name == that_label_field).length == 0) {
              select_columns.push({
                "name": that_label_field,
                "label": field.related.label,
                "searchable": true,
                "sortable": true
              })
            }
            if (extra_columns) {
              extra_columns.forEach(item => { //选择时的列默认可检索
                select_columns.push({
                  "name": item.name,
                  "label": item.label,
                  "searchable": true,
                  "sortable": true
                })
              })
            }
            let add_and_quickedit_set = prop.related && prop.related.tree_select ?
              {
                "type": "tree-select",
                "name": field.name,
                "searchable": true,
                "onlyChildren": true,
                "showIcon": false,
                "source": {
                  "method": "post",
                  "url": cfg.api_server + "tree/build",
                  "data": { tree: prop.related.tree_select }
                }
              }
              :
              {
                "type": "picker",
                "source": {
                  "method": "post",
                  "url": cfg.api_server + "datamodel/getrows",
                  "requestAdaptor": function (api) {
                    if (api.data.op == "loadOptions") {
                      let option_value = api.data.value;
                      api.data = {
                        filter: [{ key: that_field, value: option_value, like: false }]
                      }
                    }
                    else {
                      requestAdaptor(api, select_columns);
                    }
                    api.data.datamodel = field.related.datamodel;
                    api.data.tablename = field.related.model_table_name;
                    //默认的排序，如果没有设置，需要使用默认
                    if (!api.data.orderby && orderby) {
                      api.data.orderby = orderby;
                      api.data.orderdir = orderdir;
                    }
                    //默认的过滤条件
                    if (filterby) {
                      if (!api.data.filter) {
                        api.data.filter = [];
                      }
                      api.data.filter.push({
                        key: filterby,
                        like: false,
                        value: filtervalue
                      })
                    }
                  }
                },
                "valueField": that_field,
                "labelField": that_label_field,
                "size": "md",
                "pickerSchema": {
                  "mode": "table",
                  "affixHeader": false,
                  "syncLocation": false,
                  "perPage": 10,
                  "name": "thelist",
                  "columns": select_columns
                }
              }
            add_form_control = Object.assign(add_form_control, add_and_quickedit_set);
            if (prop.quickedit) {
              col.quickEdit = add_and_quickedit_set;
              col.quickEdit.autoFill = {};
              col.quickEdit.autoFill["#" + col.name] = prop.related && prop.related.tree_select ? "${label}" : "${" + field.related.that_label_field + "}";
            }
          }
          keywords_col.label_tpl = prop.label_tpl;
        }

        //id和name、title列可点击
        if(field.name=="id" || field.name=="name"  || field.name=="title"){
          col.type="operation"
          col.buttons=[
            {
              "type": "button",
              "label": "${"+col.name+"}",
              "size": "md",
              "className": "id-name-link",
              "onClick": (a, b) => open_edit_page(a,b)
            }
          ]
        }

        //添加窗口自动填入默认过滤
        if (property.default_filter) {
          let find_filter = property.default_filter.filter(f => f.key == col.name);
          if (find_filter.length > 0) {
            add_form_control.value = find_filter[0].value;
            add_form_control.disabled = true;
            col.quickEdit = false;
          }
        }
        //没有编辑权限
        if (!r_edit) col.quickEdit = false;
        columns.push(col);
        keywords_search_columns.push(keywords_col);

        //新增窗口的分组处理
        if (!field.is_sys_field) {
          if (property_column.length > 0 && property_column[0].add_form_group) {
            let property = property_column[0];
            let group_no = property.add_form_group.toString();
            if (group_no != pre_group_no) {
              let new_group_no = group_no + "_" + Math.random();
              add_form_controls_group[new_group_no] = [];
              pre_group = add_form_controls_group[new_group_no];
            }
            pre_group.push(add_form_control);
            pre_group_no = group_no;
          }
          else {
            let group_no = "not_in_group_" + Math.random();
            add_form_controls_group[group_no] = [add_form_control];
            pre_group = add_form_controls_group[group_no];
            pre_group_no = null;
          }
        }

        //----extjs----
        if (extjs.after_handle_a_field) {
          extjs.after_handle_a_field(field, col);
        }

      } //// end foreach fields
      //对添加窗口的分组处理
      for (let group_controls of Object.values(add_form_controls_group)) {
        let group = {
          "type": "group",
          "controls": group_controls
        };
        add_form_controls.push(group);
      }
      let operation_col = {
        "type": "operation",
        "name": "_operation",
        "label": "操作",
        "buttons": r_del && !property.dis_deletable ? [
          {
            "type": "button",
            "icon": "fa fa-times text-danger",
            "tooltip": "删除",
            "actionType": "ajax",
            "confirmText": "删除之后不能恢复，确认要删除？",
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/delete",
              "requestAdaptor": function (api) {api.data={
                datamodel: datamodel,
                tablename: tablename,
                id: api.data.id
              }
              }
            }
          }
        ] : []
      }
      //编辑（含子表）按钮
      if (r_edit && !property.dis_editable) {
        operation_col.buttons.unshift({
          "type": "button",
          "icon": "fa fa-edit",
          "tooltip": "编辑",
          "onClick": (a, b) => open_edit_page(a,b)
        })
      }
      if (operation_col.buttons && operation_col.buttons.length > 0) {
        columns.push(operation_col);
      }

      //----extjs----
      if (extjs.after_handle_operation_col) {
        extjs.after_handle_operation_col(operation_col);
      }

      let bulkActions=[];
      if(property.batch_delete){
        bulkActions.push(
          {
            "label": "批量删除",
            "actionType": "ajax",
            "confirmText": "删除之后不能恢复，确定要批量删除?",
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/delete",
              "requestAdaptor": function (api) {
                api.data={
                  datamodel: datamodel,
                  tablename: tablename,
                  ids: api.data.ids
                }
              }
            }
          }
        )
      }

      let extraButtons=[];
      if(property.export){
        extraButtons.push(
          {
            "type": "export-excel",
            "label": "导出Excel",
            "filename": modelname,
            "actionType": "ajax",
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/getrows",
              "requestAdaptor": function (api) {
                let ignores = ['items',"count","total","page","selectedItems","unSelectedItems"]
                requestAdaptor(api, ignores);
                api.data.perpage=10000; //暂时最多导出10000条数据
                api.data.page=1;
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
                if (property.leveled) api.data.leveled = property.leveled;
                if (property.leveled_sub_mode) api.data.leveled_sub_mode = property.leveled_sub_mode;
                api.data.keywords_search_columns = keywords_search_columns;
                //如果查询的字段是关联字段，将字段名前加#，后台根据此判断查询本表还是关联表
                if (api.data.filter) {
                  api.data.filter.forEach(f => {
                    let find_filed = fields.filter(field => field.name == f.key);
                    if (find_filed.length > 0 && find_filed[0].related) {
                      f.key = "#" + f.key;
                    }
                  })
                  api.data.filter=api.data.filter.filter(f=>(f.value!='')); //去掉为''的查询项, amis对一个字段查询后再清空会保留一个''的查询
                }
                keywords_search_columns.forEach(col => {
                  let find_filed = fields.filter(field => field.name == col.name);
                  if (find_filed.length > 0 && find_filed[0].related) {
                    col.name = "#" + col.name;
                  }
                })
                //默认的过滤被加到filter中
                if (property.default_filter) api.data.filter = property.default_filter.concat(api.data.filter);
                //默认的排序，如果没有设置，需要使用默认
                if (!api.data.orderby && property.orderby) {
                  api.data.orderby = property.orderby;
                  api.data.orderdir = property.orderdir;
                }
              }
            }
          }
        )
      }


      let amisJSON =
      {
        "cssVars": {
          "--Panel-marginBottom": "0.5rem",
          "--Form-control-widthBase": "20rem"
        },
        "type": "page",
        "name": page_html_id,
        "className": "data-model-edit-page",
        "body": [
          {
            "type": "crud",
            "name": "main_crud_in_" + page_html_id,
            "affixHeader": false,
            "syncLocation": false,
            "perPage": perpage,
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/getrows",
              "requestAdaptor": function (api) {
                let ignores = ['items']
                requestAdaptor(api, ignores);
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
                if (property.leveled) api.data.leveled = property.leveled;
                if (property.leveled_sub_mode) api.data.leveled_sub_mode = property.leveled_sub_mode;
                api.data.keywords_search_columns = keywords_search_columns;
                //如果查询的字段是关联字段，将字段名前加#，后台根据此判断查询本表还是关联表
                if (api.data.filter) {
                  api.data.filter.forEach(f => {
                    let find_filed = fields.filter(field => field.name == f.key);
                    if (find_filed.length > 0 && find_filed[0].related) {
                      f.key = "#" + f.key;
                    }
                  })
                  api.data.filter=api.data.filter.filter(f=>(f.value!='')); //去掉为''的查询项, amis对一个字段查询后再清空会保留一个''的查询
                }
                keywords_search_columns.forEach(col => {
                  let find_filed = fields.filter(field => field.name == col.name);
                  if (find_filed.length > 0 && find_filed[0].related) {
                    col.name = "#" + col.name;
                  }
                })
                //默认的过滤被加到filter中
                if (property.default_filter) api.data.filter = property.default_filter.concat(api.data.filter);
                //默认的排序，如果没有设置，需要使用默认
                if (!api.data.orderby && property.orderby) {
                  api.data.orderby = property.orderby;
                  api.data.orderdir = property.orderdir;
                }
              }
            },
            "quickSaveApi": {
              "method": "post",
              "url": cfg.api_server + "datamodel/update",
              "requestAdaptor": function (api) {
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
                for (let row of api.data.rowsDiff) {
                  utils.handlepassword(row, property.columns);
                }
              }
            },
            "keepItemSelectionOnPageChange": true,
            "maxKeepItemSelectionLength": 11,
            "expandConfig": {
              "expand": "all",
              "accordion": false
            },
            "filter": {
              "submitText": "",
              "controls": [
                {
                  "type": "text",
                  "name": "keywords",
                  "placeholder": "通过关键字搜索",
                  "clearable": true,
                  "addOn": {
                    "label": "搜索",
                    "type": "submit"
                  }
                },
                {
                  "type": "button",
                  "label": "刷新",
                  "icon": "fa fa-refresh",
                  "actionType": "reload",
                  "target": "main_crud_in_" + page_html_id
                },
                {
                  "type": "html",
                  "html": property.tip ? "<span class='tip'><i class='fa fa-info-circle'></i> " + property.tip + "</span>" : ""
                }
              ]
            },
            "filterTogglable": true,
            "bulkActions": bulkActions,
            "headerToolbar": [
              {
                "type": "button",
                "actionType": "dialog",
                "label": "新增",
                "visible": r_add  && !property.dis_addable,
                "icon": "fa fa-plus pull-left",
                "primary": true,
                "dialog": {
                  "title": "新" + modelname,
                  "size": "lg",
                  "className": "crud-add-dialog crud-add-dialog-" + datamodel,
                  "body": {
                    "type": "form",
                    "name": "add-form",
                    "className": "modal-add-form",
                    "mode": "normal",
                    "api": {
                      "method": "post",
                      "url": cfg.api_server + "datamodel/add",
                      "requestAdaptor": function (api) {
                        let newrow = api.data;
                        utils.handlepassword(newrow, property.columns);
                        for (let key of Object.keys(newrow)) { //config字段，被包在同名combo中，需要解开
                          let find_col = property.columns.filter(col => col.name == key);
                          if (find_col.length > 0 && find_col[0].type == "config") {
                            newrow[key] = newrow[key][key] ? newrow[key][key] : JSON.stringify(newrow[key].configer);
                          }
                        }
                        api.data = {
                          rows: [newrow]
                        }
                        api.data.datamodel = datamodel;
                        api.data.tablename = tablename;
                      }
                    },
                    "controls": add_form_controls
                  }
                }
              },
              "bulkActions",
              ...extraButtons,
              {
                "type": "columns-toggler",
                "align": "right"
              },
              {
                "type": "pagination",
                "align": "right"
              },
              {
                "type": "tpl",
                "tpl": "当前有 ${count} 条数据",
                "className": "v-middle",
                "align": "right"
              }
            ],
            "footerToolbar": [
              "statistics",
              "switch-per-page",
              "pagination"
            ],
            "columns": columns
          }
        ]
      }
      let amis = amisRequire('amis/embed');

      //----extjs----
      if (extjs.before_amis_embed) {
        extjs.before_amis_embed(amisJSON);
      }

      let amisScoped = amis.embed(
        '#' + page_html_id, amisJSON, {},
        {
          theme: 'antd'
        }
      );

      //不打印的元素
      $('#' + page_html_id+ " .antd-Crud-filter").addClass("noprint");
      $('#' + page_html_id+ " .antd-Table-headToolbar button").addClass("noprint");
    })
  }
}

export default page_type;